#!/bin/bash
base=$(cd $(dirname $0);pwd)
script_home=${base%/script*}
custom="${script_home%/*}/custom_result.yml"
nacos_path="${script_home%/common*}/snc_product/nacos"
common_path="${nacos_path}/COMMON_GROUP"
default_path="${nacos_path}/DEFAULT_GROUP"

nacos_ip=$(grep '^nacos_ip:' "$custom" | awk '{print $2}' | tr -d '"')
nacos_port=$(grep '^nacos_port:' "$custom" | awk '{print $2}' | tr -d '"')
nacos_pwd=$(grep '^nacos_pwd:' "$custom" | awk '{print $2}' | tr -d '"')

nacos_url="http://${nacos_ip}:${nacos_port}"

#压缩
cd ${nacos_path}
rm -rf ${nacos_path}/nacos_config.zip
zip -r nacos_config.zip COMMON_GROUP DEFAULT_GROUP

nacos_file="${nacos_path}/nacos_config.zip"
#获取token
login_info=$(curl -s -X POST "${nacos_url}/nacos/v1/auth/login" -d 'username=nacos&password=nacos')
echo "登录成功：$login_info"
login_token=$(echo $login_info | awk -F':' '{print $2}' | awk -F',' '{print $1}'| sed 's/"//g')
echo "token是：$login_token"
#创建ns
echo "curl -s -X POST \"${nacos_url}/nacos/v1/console/namespaces?accessToken=${login_token}\" -d \"customNamespaceId=shsnc_product&namespaceName=shsnc_product&namespaceDesc=shsnc_product\""
ns_res=$(curl -s -X POST "${nacos_url}/nacos/v1/console/namespaces?accessToken=${login_token}" -d "customNamespaceId=shsnc_product&namespaceName=shsnc_product&namespaceDesc=shsnc_product")
echo "创建命名空间状态：$ns_res"
if [ "${ns_res}" == "true" ]; then
	echo "shsnc_product命名空间创建成功"
fi

import_res=$(curl -s -X POST "${nacos_url}/nacos/v1/cs/configs?import=true&namespace=shsnc_product&policy=OVERWRITE" -H "Content-Type: multipart/form-data" -F "file=@${nacos_file}" -H "Authorization: Bearer ${login_token}")
import_res_msg=$(echo $import_res | awk -F':' '{print $2}' | awk -F',' '{print $1}')
if [ "${import_res_msg}" == "200" ]; then
	echo "nacos配置文件导入成功"
fi

#修改密码
update_pwd=$(curl -s -X PUT "${nacos_url}/nacos/v1/auth/users?username=nacos&newPassword=${nacos_pwd}&accessToken=${login_token}")
update_pwd_msg=$(echo $update_pwd | awk -F':' '{print $2}' | awk -F',' '{print $1}')
if [ "${update_pwd_msg}" == "200" ]; then
	echo "nacos密码修改成功"
fi
